package com.esun.cheetah.view.setting;

import java.util.Properties;

import com.esun.cheetah.config.Config;
import com.esun.cheetah.view.setting.service.NotificationService;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

public class ServiceManager {
	private Context context;
	private Properties props;
	private String version = "0.5.0";
	private String apiKey;
	private String xmppHost;
	private String xmppPort;
	private String callbackActivityPackageName;
	private String callbackActivityClassName;
	SharedPreferences sharedPrefs;

	public ServiceManager(Context context) {
		this.context = context;

		if (context instanceof Activity) {
			Activity callbackActivity = (Activity) context;
			callbackActivityPackageName = callbackActivity.getPackageName();
			callbackActivityClassName = callbackActivity.getClass().getName();
		}
		props = loadProperties();
		apiKey = props.getProperty("apiKey", "");
		xmppHost = props.getProperty("xmppHost", "127.0.0.1");
		xmppPort = props.getProperty("xmppPort", "5222");
		saveProperties();
	}

	/**
	 * 保存参数信息 到本地
	 */
	private void saveProperties() {
		sharedPrefs = context.getSharedPreferences(
				Config.SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
		Editor editor = sharedPrefs.edit();
		editor.putString(Config.API_KEY, apiKey);
		editor.putString(Config.VERSION, version);
		editor.putString(Config.XMPP_HOST, xmppHost);
		editor.putInt(Config.XMPP_PORT, Integer.parseInt(xmppPort));
		editor.putString(Config.CALLBACK_ACTIVITY_PACKAGE_NAME,
				callbackActivityPackageName);
		editor.putString(Config.CALLBACK_ACTIVITY_CLASS_NAME,
				callbackActivityClassName);
		editor.commit();

	}

	/**
	 * 获取ApiKey ip,端口号
	 * 
	 * @return
	 */
	private Properties loadProperties() {
		Properties props = new Properties();
		try {
			int id = context.getResources().getIdentifier("androidpn", "raw",
					context.getPackageName());
			props.load(context.getResources().openRawResource(id));
		} catch (Exception e) {
		}
		return props;
	}

	/**
	 * 开启服务
	 */
	public void startService() {
		Thread serviceThread = new Thread(new Runnable() {
			@Override
			public void run() {
				Intent intent = new Intent(context, NotificationService.class);
				context.startService(intent);
			}
		});
		serviceThread.start();
	}

	public void setNotificationIcon(int iconId) {
		Editor editor = sharedPrefs.edit();
		editor.commit();
	}
}
